
package com.sunwayworld.basemodule.common.utils;

import com.aspose.words.Document;
import com.aspose.words.HtmlSaveOptions;
import com.deepoove.poi.util.ByteUtils;
import com.rtfparserkit.converter.text.StringTextConverter;
import com.rtfparserkit.parser.RtfStreamSource;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.exception.FileException;
import com.sunwayworld.framework.io.excel.ExcelHelper;
import com.sunwayworld.framework.io.file.FilePathDTO;
import com.sunwayworld.framework.io.file.FilePathManager;
import com.sunwayworld.framework.utils.EncodingUtils;
import com.sunwayworld.framework.utils.ObjectUtils;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.module.item.file.bean.CoreFileBean;
import com.sunwayworld.module.item.file.utils.CoreFileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.converter.AbstractWordUtils;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.util.XMLHelper;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.core.env.Environment;
import org.w3c.dom.Element;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.*;

public class FileUtils {
    public static final String FILE_ROOT_DIR_NAME = "files";

    public FileUtils() {
    }

    public static String getBase64StrByPath(String filePath) throws IOException {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(filePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            throw e;
        } finally {
            if (in != null)
                in.close();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return data != null ? encoder.encode(data) : "";
    }

    public static final void write(File file, String content) {
        try {
            FileWriter writer = new FileWriter(file);
            Throwable var3 = null;

            try {
                writer.write(content);
                writer.flush();
            } catch (Throwable var13) {
                var3 = var13;
                throw var13;
            } finally {
                if (writer != null) {
                    if (var3 != null) {
                        try {
                            writer.close();
                        } catch (Throwable var12) {
                            var3.addSuppressed(var12);
                        }
                    } else {
                        writer.close();
                    }
                }

            }

        } catch (IOException var15) {
            throw new FileException(var15);
        }
    }

    public static final void write(File file, InputStream is) {
        try {
            FileOutputStream fos = new FileOutputStream(file);
            Throwable var3 = null;

            try {
                byte[] buffer = new byte[4096048];
                boolean var5 = false;

                int size;
                while ((size = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, size);
                }
            } catch (Throwable var14) {
                var3 = var14;
                throw var14;
            } finally {
                if (fos != null) {
                    if (var3 != null) {
                        try {
                            fos.close();
                        } catch (Throwable var13) {
                            var3.addSuppressed(var13);
                        }
                    } else {
                        fos.close();
                    }
                }

            }

        } catch (IOException var16) {
            throw new FileException(var16);
        }
    }

    public static final List<String> readAllLines(File file) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            Throwable var2 = null;

            try {
                List<String> lineList = new ArrayList();
                String line = null;

                while ((line = br.readLine()) != null) {
                    lineList.add(line);
                }

                return lineList;
            } catch (Throwable var15) {
                var2 = var15;
                throw var15;
            } finally {
                if (br != null) {
                    if (var2 != null) {
                        try {
                            br.close();
                        } catch (Throwable var14) {
                            var2.addSuppressed(var14);
                        }
                    } else {
                        br.close();
                    }
                }

            }
        } catch (IOException var17) {
            throw new FileException(var17);
        }
    }

    public static final void createFile(File file) {
        if (!file.exists()) {
            file.getParentFile().mkdirs();

            try {
                file.createNewFile();
            } catch (IOException var2) {
                throw new FileException(var2);
            }
        }
    }

    /**
     * 读取rtf文件
     */
    private static String extractTextFromRtf(File file) {
        StringTextConverter converter = new StringTextConverter();
        try {
            converter.convert(new RtfStreamSource(new FileInputStream(file)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String extractedText = converter.getText();
        return ObjectUtils.toString(extractedText);
    }

    public static final String getFileExtension(String fileName) {
        return getFileExtension(Paths.get(fileName));
    }

    public static final String getFileExtension(File file) {
        return getFileExtension(file.toPath());
    }

    public static final String getFileExtension(Path path) {
        String fileName = path.getFileName().toString();
        return fileName.indexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static final String getFileBaseName(File file) {
        return getFileBaseName(file.toPath());
    }

    public static final String getFileBaseName(Path path) {
        String fileName = path.getFileName().toString();
        return getFileBaseName(fileName);
    }

    public static String getFileBaseName(String fileName) {
        return fileName.indexOf(".") == -1 ? fileName : fileName.substring(0, fileName.lastIndexOf("."));
    }

    public static void deleteRecursively(Path path) {
        if (Files.isDirectory(path, new LinkOption[0])) {
            try {
                Files.list(path).forEach((p) -> {
                    deleteRecursively(p);
                });
                Files.deleteIfExists(path);
            } catch (IOException var3) {
                throw new FileException(var3);
            }
        } else {
            try {
                Files.deleteIfExists(path);
            } catch (IOException var2) {
                throw new FileException(var2);
            }
        }

    }

    public static void deleteQuietly(File file) {
        if (file != null) {
            try {
                file.delete();
            } catch (Exception var2) {
            }
        }

    }

    public static final boolean isInJarURL(URL url) {
        return StringUtils.contains(url.getPath(), ".jar!");
    }

    public static List<File> getFileList(Path dir) {
        if (!Files.isDirectory(dir, new LinkOption[0])) {
            return Collections.emptyList();
        } else {
            final ArrayList fileList = new ArrayList();

            try {
                Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        fileList.add(file.toFile());
                        return FileVisitResult.CONTINUE;
                    }
                });
                return fileList;
            } catch (IOException var3) {
                throw new FileException(var3);
            }
        }
    }

    public static final String makeValidFilename(String name) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < name.length(); ++i) {
            char c = name.charAt(i);
            switch (c) {
                case ' ':
                    sb.append("_");
                case '"':
                case '*':
                case '/':
                case ':':
                case '<':
                case '>':
                case '?':
                case '\\':
                case '|':
                    break;
                default:
                    sb.append(c);
            }
        }

        return sb.toString();
    }

    public static final void encode(String srcFile, String destFile, Charset targetCharset) {
        try {
            FileInputStream fis = new FileInputStream(srcFile);
            Throwable var4 = null;

            try {
                DataInputStream in = new DataInputStream(fis);
                Throwable var6 = null;

                try {
                    BufferedReader d = new BufferedReader(new InputStreamReader(in, EncodingUtils.detect(srcFile)));
                    StringBuilder sb = new StringBuilder();

                    for (String line = null; (line = d.readLine()) != null; sb.append(line)) {
                        if (sb.length() != 0) {
                            sb.append(System.lineSeparator());
                        }
                    }

                    File outFile = new File(destFile);

                    try {
                        Files.createDirectories(outFile.getParentFile().toPath());
                        outFile.createNewFile();
                    } catch (IOException var63) {
                        throw new FileException(var63);
                    }

                    Writer ow = new OutputStreamWriter(new FileOutputStream(outFile), targetCharset);
                    Throwable var12 = null;

                    try {
                        ow.write(sb.toString());
                    } catch (Throwable var62) {
                        var12 = var62;
                        throw var62;
                    } finally {
                        if (ow != null) {
                            if (var12 != null) {
                                try {
                                    ow.close();
                                } catch (Throwable var61) {
                                    var12.addSuppressed(var61);
                                }
                            } else {
                                ow.close();
                            }
                        }

                    }
                } catch (Throwable var65) {
                    var6 = var65;
                    throw var65;
                } finally {
                    if (in != null) {
                        if (var6 != null) {
                            try {
                                in.close();
                            } catch (Throwable var60) {
                                var6.addSuppressed(var60);
                            }
                        } else {
                            in.close();
                        }
                    }

                }
            } catch (Throwable var67) {
                var4 = var67;
                throw var67;
            } finally {
                if (fis != null) {
                    if (var4 != null) {
                        try {
                            fis.close();
                        } catch (Throwable var59) {
                            var4.addSuppressed(var59);
                        }
                    } else {
                        fis.close();
                    }
                }

            }

        } catch (IOException var69) {
            throw new FileException(var69);
        }
    }

    public static String extractTextFromFile(File file) {
        String var1 = getFileExtension(file.getName()).toLowerCase();
        byte var2 = -1;
        switch (var1.hashCode()) {
            case 113252:
                if (var1.equals("rtf")) {
                    var2 = 7;
                }
                break;
            case 98822:
                if (var1.equals("csv")) {
                    var2 = 2;
                }
                break;
            case 99640:
                if (var1.equals("doc")) {
                    var2 = 3;
                }
                break;
            case 110834:
                if (var1.equals("pdf")) {
                    var2 = 5;
                }
                break;
            case 115312:
                if (var1.equals("txt")) {
                    var2 = 6;
                }
                break;
            case 118783:
                if (var1.equals("xls")) {
                    var2 = 0;
                }
                break;
            case 3088960:
                if (var1.equals("docx")) {
                    var2 = 4;
                }
                break;
            case 3682393:
                if (var1.equals("xlsx")) {
                    var2 = 1;
                }
        }

        switch (var2) {
            case 0:
                return extractTextFromXls(file);
            case 1:
                return extractTextFromXlsx(file);
            case 2:
                return extractTextFromCsv(file);
            case 3:
                return extractTextFromDoc(file);
            case 4:
                return extractTextFromDocx(file);
            case 5:
                return extractTextFromPDF(file);
            case 6:
                return extractTextFromTxt(file);
            case 7:
                return extractTextFromRtf(file);
            default:
                return "";
        }
    }

    private static String extractTextFromXls(File file) {
        HSSFWorkbook wb = null;

        try {
            InputStream is = new BufferedInputStream(new FileInputStream(file));
            Throwable var3 = null;

            try {
                wb = new HSSFWorkbook(is);
                int sheetNum = wb.getNumberOfSheets();
                StringBuilder sb = new StringBuilder();

                for (int sheetNo = 0; sheetNo < sheetNum; ++sheetNo) {
                    HSSFSheet sheet = wb.getSheetAt(sheetNo);
                    if (!wb.isSheetHidden(sheetNo)) {
                        int endRowNum = sheet.getLastRowNum();

                        for (int rowNum = sheet.getFirstRowNum(); rowNum <= endRowNum; ++rowNum) {
                            HSSFRow row = sheet.getRow(rowNum);
                            if (row != null) {
                                for (int cellIndex = row.getFirstCellNum(); cellIndex <= row.getLastCellNum(); ++cellIndex) {
                                    HSSFCell cell = row.getCell(cellIndex);
                                    String value = (String) ExcelHelper.getCellValue(cell, String.class);
                                    if ("".equals(value)) {
                                        value = "\t";
                                    }

                                    sb.append(" ").append(value);
                                }

                                sb.append("\r\n");
                            }
                        }
                    }
                }

                String var39 = sb.toString();
                return var39;
            } catch (Throwable var35) {
                var3 = var35;
                throw var35;
            } finally {
                if (is != null) {
                    if (var3 != null) {
                        try {
                            is.close();
                        } catch (Throwable var34) {
                            var3.addSuppressed(var34);
                        }
                    } else {
                        is.close();
                    }
                }

            }
        } catch (IOException var37) {
            throw new FileException(var37);
        } finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (Exception var33) {
                }
            }

        }
    }

    private static String extractTextFromXlsx(File file) {
        XSSFWorkbook wb = null;

        try {
            InputStream is = new BufferedInputStream(new FileInputStream(file));
            Throwable var3 = null;

            try {
                wb = new XSSFWorkbook(is);
                int sheetNum = wb.getNumberOfSheets();
                StringBuilder sb = new StringBuilder();

                for (int sheetNo = 0; sheetNo < sheetNum; ++sheetNo) {
                    XSSFSheet sheet = wb.getSheetAt(sheetNo);
                    if (!wb.isSheetHidden(sheetNo)) {
                        int endRowNum = sheet.getLastRowNum();

                        for (int rowNum = sheet.getFirstRowNum(); rowNum <= endRowNum; ++rowNum) {
                            XSSFRow row = sheet.getRow(rowNum);
                            if (row != null) {
                                int columnQty = row.getPhysicalNumberOfCells();

                                for (int cellIndex = 0; cellIndex < columnQty; ++cellIndex) {
                                    XSSFCell cell = row.getCell(cellIndex);
                                    String value = (String) ExcelHelper.getCellValue(cell, String.class);
                                    if ("".equals(value)) {
                                        value = "\t";
                                    }
                                    if (cellIndex == 0) {
                                        sb.append(value);
                                    } else {
                                        sb.append("\t").append(value);
                                    }
                                }

                                sb.append("\r\n");
                            }
                        }
                    }
                }

                String var40 = sb.toString();
                return var40;
            } catch (Throwable var36) {
                var3 = var36;
                throw var36;
            } finally {
                if (is != null) {
                    if (var3 != null) {
                        try {
                            is.close();
                        } catch (Throwable var35) {
                            var3.addSuppressed(var35);
                        }
                    } else {
                        is.close();
                    }
                }

            }
        } catch (IOException var38) {
            throw new FileException(var38);
        } finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException var34) {
                }
            }

        }
    }

    private static String extractTextFromCsv(File file) {
        BufferedReader br = null;
        DataInputStream in = null;
        StringBuilder sb = new StringBuilder();

        try {
            in = new DataInputStream(new FileInputStream(file));
            br = new BufferedReader(new InputStreamReader(in, EncodingUtils.detect(file)));

            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\r\n");
            }

            String var5 = sb.toString();
            return var5;
        } catch (Exception var17) {
            throw new FileException(var17);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException var16) {
                }
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException var15) {
                }
            }

        }
    }

    private static String extractTextFromDoc(File file) {
        FileInputStream ins = null;
        WordExtractor ex = null;

        String var3;
        try {
            ins = new FileInputStream(file);
            ex = new WordExtractor(ins);
            var3 = ex.getText();
        } catch (IOException var15) {
            throw new FileException(var15);
        } finally {
            if (ex != null) {
                try {
                    ex.close();
                } catch (IOException var14) {
                }
            }

            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException var13) {
                }
            }

        }

        return var3;
    }

    private static String extractTextFromDocx(File file) {
        FileInputStream ins = null;
        XWPFWordExtractor extractor = null;

        String var4;
        try {
            ins = new FileInputStream(file);
            XWPFDocument xdoc = new XWPFDocument(ins);
            extractor = new XWPFWordExtractor(xdoc);
            var4 = extractor.getText();
        } catch (IOException var16) {
            throw new FileException(var16);
        } finally {
            if (extractor != null) {
                try {
                    extractor.close();
                } catch (IOException var15) {
                }
            }

            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException var14) {
                }
            }

        }

        return var4;
    }

    public static String extractTextFromTxt(File file) {
        FileInputStream ins = null;
        BufferedInputStream bi = null;
        StringBuilder sb = new StringBuilder();

        try {
            ins = new FileInputStream(file);
            bi = new BufferedInputStream(ins);
            byte[] byteArray = new byte[4096];
            String charset = EncodingUtils.detect(file);

            int length;
            while ((length = bi.read(byteArray)) != -1) {
                sb.append(new String(byteArray, 0, length, charset));
            }

            String var7 = sb.toString();
            return var7;
        } catch (IOException var19) {
            throw new FileException(var19);
        } finally {
            if (bi != null) {
                try {
                    bi.close();
                } catch (IOException var18) {
                }
            }

            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException var17) {
                }
            }

        }
    }

    private static String extractTextFromPDF(File file) {
        PDDocument pdfDocument = null;

        String var3;
        try {
            pdfDocument = PDDocument.load(file);
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(true);
            var3 = stripper.getText(pdfDocument);
        } catch (IOException var12) {
            throw new FileException(var12);
        } finally {
            if (pdfDocument != null) {
                try {
                    pdfDocument.close();
                } catch (IOException var11) {
                }
            }

        }
        return var3;
    }

    //转文件为富文本
    public static String extractRichTextFromFile(File file) {
        String var1 = getFileExtension(file.getName()).toLowerCase();
        byte var2 = -1;
        switch (var1.hashCode()) {
            case 113252:
                if (var1.equals("rtf")) {
                    var2 = 7;
                }
                break;
            case 98822:
                if (var1.equals("csv")) {
                    var2 = 2;
                }
                break;
            case 99640:
                if (var1.equals("doc")) {
                    var2 = 3;
                }
                break;
            case 110834:
                if (var1.equals("pdf")) {
                    var2 = 5;
                }
                break;
            case 115312:
                if (var1.equals("txt")) {
                    var2 = 6;
                }
                break;
            case 118783:
                if (var1.equals("xls")) {
                    var2 = 0;
                }
                break;
            case 3088960:
                if (var1.equals("docx")) {
                    var2 = 4;
                }
                break;
            case 3682393:
                if (var1.equals("xlsx")) {
                    var2 = 1;
                }
        }

        switch (var2) {
            case 0:
                return extractRichTextFromXls(file);
            case 1:
                return extractRichTextFromXlsx(file);
            case 2:
                return extractRichTextFromCsv(file);
            case 3:
                return extractRichTextFromDoc(file);
            case 4:
                return extractRichTextFromDocx(file);
            case 5:
                return extractRichTextFromPDF(file);
            case 6:
                return extractRichTextFromTxt(file);
            case 7:
                return extractRichTextFromRtf(file);
            default:
                return "";
        }
    }

    public static String extractRichTextFromXls(File file) {
        return "";
    }

    public static String extractRichTextFromXlsx(File file) {
        return "";
    }

    public static String extractRichTextFromCsv(File file) {
        return "";
    }

    public static class ImageConverter extends WordToHtmlConverter {
        public ImageConverter(org.w3c.dom.Document document) {
            super(document);
        }

        @Override
        protected void processImageWithoutPicturesManager(Element currentBlock, boolean inlined, Picture picture) {
            Element imgNode = currentBlock.getOwnerDocument().createElement("img");
            StringBuffer sb = new StringBuffer();
            sb.append(Base64.getMimeEncoder().encodeToString(picture.getRawContent()));
            sb.insert(0, "data:" + picture.getMimeType() + ";base64,");
            imgNode.setAttribute("src", sb.toString());
            currentBlock.appendChild(imgNode);
        }
    }

    private static org.w3c.dom.Document process(File docFile) throws IOException, ParserConfigurationException {
        DocumentBuilder docBuild = XMLHelper.getDocumentBuilderFactory().newDocumentBuilder();
        HWPFDocumentCore wordDocument = AbstractWordUtils.loadDoc(docFile);
        Throwable var3 = null;

        org.w3c.dom.Document var5;
        try {
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(docBuild.newDocument());
            wordToHtmlConverter.processDocument(wordDocument);
            var5 = wordToHtmlConverter.getDocument();
        } catch (Throwable var14) {
            var3 = var14;
            throw var14;
        } finally {
            if (wordDocument != null) {
                if (var3 != null) {
                    try {
                        wordDocument.close();
                    } catch (Throwable var13) {
                        var3.addSuppressed(var13);
                    }
                } else {
                    wordDocument.close();
                }
            }

        }

        return var5;
    }

    public static String extractRichTextFromDoc(File file) {
        try {
            org.w3c.dom.Document doc = process(file);
            DOMSource domSource = new DOMSource(doc);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            StreamResult streamResult = new StreamResult(out);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer serializer = tf.newTransformer();
            serializer.setOutputProperty("encoding", "UTF-8");
            serializer.setOutputProperty("indent", "yes");
            serializer.setOutputProperty("method", "html");
            serializer.transform(domSource, streamResult);
            String result = new String(out.toByteArray());
            out.close();
            org.apache.commons.io.FileUtils.writeStringToFile(new File("C:\\Users\\think\\Desktop\\", "cc.html"), result, "utf-8");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String extractRichTextFromDocx(File file) {
        try {
            HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(file));
            org.w3c.dom.Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);
            wordToHtmlConverter.processDocument(wordDocument);
            org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult(new File("C:\\Users\\think\\Desktop\\cc.html"));
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer serializer = tf.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String extractRichTextFromPDF(File file) {
        return "123";
    }

    public static String extractRichTextFromTxt(File file) {
        return "123";
    }

    /**
     * 通过读取文件并获取其width及height的方式，来判断判断当前文件是否图片，这是一种非常简单的方式。
     *
     * @param imageFile
     * @return
     */
    public static boolean isImage(File imageFile) {
        if (!imageFile.exists()) {
            return false;
        }
        Image img = null;
        try {
            img = ImageIO.read(imageFile);
            if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            img = null;
        }
    }

    public static String extractRichTextFromRtf(File file) {
        try {
            Document doc = new Document(file.getAbsolutePath());//path为word地址
            HtmlSaveOptions hso = new HtmlSaveOptions();
            hso.setExportRoundtripInformation(true);
            hso.setExportImagesAsBase64(true);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            doc.save(stream, hso);
            String s = stream.toString();
            if (stream != null) {
                stream.close();
            }
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //将Byte数组转换成文件
    public static void getFileByBytes(byte[] bytes, String filePath) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath).getParentFile();
            if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将PDF按页数每页转换成一个jpg图片
     *
     * @return
     */
    public static List<String> pdfToImagePath(String pdfFilePath, String imgDirPath) {
        List<String> list = new ArrayList<>();
        try {
            File pdfFile = new File(pdfFilePath);
            PDDocument doc = PDDocument.load(pdfFile);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                // 方式1,第二个参数是设置缩放比(即像素)
                // BufferedImage image = renderer.renderImageWithDPI(i, 296);
                // 方式2,第二个参数是设置缩放比(即像素)
                BufferedImage image = renderer.renderImage(i, 1.25f); // 第二个参数越大生成图片分辨率越高，转换时间也就越长
                String imgName = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase() + ".png";
                String imagePath = imgDirPath + File.separator + imgName;
                ImageIO.write(image, "PNG", new File(imagePath));
                list.add(imagePath);
            }
            doc.close(); // 关闭文件,不然该pdf文件会一直被占用。
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return list;
    }

    public static byte[] getFileByte(CoreFileBean coreFile) {
        FilePathDTO filePathDTO = CoreFileUtils.toFilePath(coreFile);
        Path absolutePath = FilePathManager.getLocalPath(filePathDTO);
        File file = absolutePath.toFile();
        if (!file.exists()) {
            return ByteUtils.getUrlByteArray(getFileServerUrl() + FilePathManager.getUrl(filePathDTO));
        }
        return ByteUtils.getLocalByteArray(absolutePath.toFile());
    }

    public static String getFileServerUrl() {
        Environment environment = ApplicationContextHelper.getBean(Environment.class);
        String url = environment.getProperty("sunway.config.file.server.url");
        if (StringUtils.isEmpty(url)) {
            return "http://localhost:" + environment.getProperty("server.port");
        }
        return url;
    }

    public static void copyFile(File source, String dest) throws IOException {
        //创建目的地文件夹
        File destfile = new File(dest);
        if (!destfile.exists()) {
            destfile.mkdir();
        }
        //如果source是文件夹，则在目的地址中创建新的文件夹
        if (source.isDirectory()) {
            File file = new File(dest + File.separator + source.getName());//用目的地址加上source的文件夹名称，创建新的文件夹
            file.mkdir();
            //得到source文件夹的所有文件及目录
            File[] files = source.listFiles();
            if (files.length == 0) {
                return;
            } else {
                for (int i = 0; i < files.length; i++) {
                    copyFile(files[i], file.getPath());
                }
            }

        }
        //source是文件，则用字节输入输出流复制文件
        else if (source.isFile()) {
            FileInputStream fis = new FileInputStream(source);
            //创建新的文件，保存复制内容，文件名称与源文件名称一致
            File dfile = new File(dest + File.separator + source.getName());
            if (!dfile.exists()) {
                dfile.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(dfile);
            // 读写数据
            // 定义数组
            byte[] b = new byte[1024];
            // 定义长度
            int len;
            // 循环读取
            while ((len = fis.read(b)) != -1) {
                // 写出数据
                fos.write(b, 0, len);
            }

            //关闭资源
            fos.close();
            fis.close();

        }
    }

}
